package org.yray.javaagent;

import com.sun.tools.attach.*;
import java.io.IOException;
import java.util.List;

public class AttachTest {
    public static void main(String []args) throws IOException, AttachNotSupportedException, AgentLoadException, AgentInitializationException {
        //获取当前系统中所有 运行中的 虚拟机
        System.out.println("running JVM start ");
        List<VirtualMachineDescriptor> list = VirtualMachine.list();
        for (VirtualMachineDescriptor vmd : list) {
            //如果虚拟机的名称为 xxx 则 该虚拟机为目标虚拟机，获取该虚拟机的 pid
            //然后加载 agent.jar 发送给该虚拟机
            if(vmd.displayName().endsWith("JustRun")){
                VirtualMachine attach = VirtualMachine.attach(vmd.id());
                //java代理包路径
                attach.loadAgent("javaagent/target/javaagent-1.0-SNAPSHOT.jar");
                try {
                    Thread.sleep(30000L);
                    //解除绑定
                    attach.detach();
                }catch (Exception e){
                }
            }
        }
    }
}